﻿using MediatR;
using PublicCommon;
using T_Material.Domain;
using T_Material.Infrastructure.ImpI;
using T_Material.Infrastructure.Interface;
using T_Material.Read.API.Application.Commands.WarehousingCommand;

namespace T_Material.Read.API.Application.CommandHandlers.WarehousingHandler
{
    public class WarehousingListCommandHandler : IRequestHandler<WarehousingListCommand, PageResult<Warehousing>>
    {
        private readonly IWarehousingRepository warehousingRepository;
        public WarehousingListCommandHandler(IWarehousingRepository wearehousingRepository)
        {
            this.warehousingRepository = wearehousingRepository;
        }
        public async Task<PageResult<Warehousing>> Handle(WarehousingListCommand request, CancellationToken cancellationToken)
        {
            var list = warehousingRepository.GetList().Result.Where(x => !x.IsDel).AsQueryable();
            if (!string.IsNullOrEmpty(request.GoodsName))
            {
                list = list.Where(x => x.GoodsName.Contains(request.GoodsName));
            }
            if (!string.IsNullOrEmpty(request.Country))
            {
                list = list.Where(x => x.Country.Contains(request.Country));
            }
            if (!string.IsNullOrEmpty(request.MateriaQluality))
            {
                list = list.Where(x => x.MateriaQluality.Contains(request.MateriaQluality)); 
            }
            if (!string.IsNullOrEmpty(request.RegPerson))
            {
                list = list.Where(x => x.RegPerson.Contains(request.RegPerson));
            }
            if (!string.IsNullOrEmpty(request.ModeOfPayment))
            {
                list = list.Where(x => x.ModeOfPayment.Contains(request.ModeOfPayment));
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var pagelist = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new PageResult<Warehousing>
            {
                List = pagelist,
                PageCount = pageCount,
                TotalCount = totalCount
            };
        }
    }
}
